var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require("fs");
var engine = require('ejs-locals');
var routes = require('./routes/index');
var login = require('./routes/login');
var logout = require('./routes/logout');
var process_order = require('./routes/process_order');
var ajax = require('./routes/ajax-loaded');
var globalFunctions =  require('./global_functions/global_functions');

//LOAD USER ROLES//RELOAD ACCESS RIGHT
var userRoles = require("./initial_load/user_roles");
    userRoles.loadAccessRights();
    
//var users = require('./routes/users');

var app = express();
app.engine('ejs', engine);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.set('view engine', 'ejs');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/stylesheets',express.static(path.join(__dirname, 'public/stylesheets')));
app.use('/javascripts',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/images',express.static(path.join(__dirname, 'public/images')));
//app.use('/', routes);


//serves as the interceptor
app.use(function(req, res, next){
    res.locals.HAS_ROLE = function(role){
    	return HAS_ROLE(req.cookies.USER_GROUP_ID, role); //hasUserRole is located in global_functions
    }
    
    res.locals.HAS_ACCESS_ROLE = function(userGroupId, role){
    	return HAS_ROLE(userGroupId, role); //hasUserRole is located in global_functions
    }
    
    //TESTING ONLY
    res.locals.currentUser = req.cookies.USER_ID;
    res.locals.currentUserFullName = req.cookies.USER_FULLNAME;
    res.locals.currentUserGroupId = req.cookies.USER_GROUP_ID;
    res.locals.currentUserGroupName = req.cookies.USER_GROUP_NAME;
    res.locals.currentBranchId = req.cookies.BRANCH_ID;
    res.locals.currentCompanyKey =  req.cookies.COMPANY_KEY;
    console.log("=================>" +  req.cookies.cookiename);
    next();
});

/*experimental*/
/*
CONVENTION
    <name>controller in controller folder
*/
var routeConfig = require('./routes/base_route');
    app.use("/:company/item", routeConfig("item"));
    app.use("/:company/aimon", routeConfig("aimon"));
    
    app.use("/", login);
    app.use("/", logout);
    app.use("/:company/backend/", routes);
    app.use("/:company/backend/backend", routeConfig("backend"));
    app.use("/:company/backend/user", routeConfig("user"));
    app.use("/:company/backend/company", routeConfig("company"));
    app.use("/:company/backend/user-group", routeConfig("user-group"));
    app.use("/:company/backend/user-permission", routeConfig("user-permission"));
    app.use("/:company/backend/settings", routeConfig("settings"));
    
    app.use("/:company/frontend/order-payment", routeConfig("order-payment"));
    app.use("/:company/process_order", process_order);
    app.use("/:company/frontend/won-auction", routeConfig("won-auction"));
    
    app.use("/:company/backend/module", routeConfig("module"));
    app.use("/:company/backend/branch", routeConfig("branch"));
    
    
    /*AJAX HERE */
    app.use("/:company/ajax", ajax);
    
    //app.use("/admin/company", routeConfig("admin"));
    /*app.use("/sample1", routeConfig("sample1"));
     app.use("/sample5", routeConfig("sample5")); */
   // app.use("/sample", routeConfig("sample"));
   //  app.use("/company", routeConfig("company"));

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var error = function(){
        console.log(req.url + " ---  " );
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    };
    error();

    /**
    This is experimental
    var url = req.url;
    var splitted = url.split("/");

    console.log("LENGTH - > " + splitted.length + " ---->" + splitted[0]);
    if(splitted != null && splitted.length >= 2){
       var target = path.join(__dirname, 'views' , splitted[1]);
        fs.exists(target, function (exists) {
          console.log("DIRECTORY: " + target );
          console.log(exists ? "it's there" : "no passwd!");
        });
    }else{
        error();
    }*/
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;
